<template>
  <div
    ref="barChart"
    class="chart-box"
    :style="{ width, height }" />
</template>

<script setup lang="ts">
import * as echarts from 'echarts'
import { ref, onMounted, watch } from 'vue'
const props = defineProps({
  width: {
    type: String,
    default: '300px'
  },
  height: {
    type: String,
    default: '300px'
  },
  xData: {
    type: Array,
    default() {
      return []
    }
  },
  yData: {
    type: Array,
    default() {
      return []
    }
  }
})

const barChart = ref<HTMLElement>()
let chart: any

// 基础图表配置
const option = {
  xAxis: {
    type: 'category',
    data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  },
  yAxis: {
    type: 'value'
  },
  color: ['#3E92FE', '#FE9D3E'],
  series: [
    {
      data: [120, 200, 150, 80, 70, 110, 130],
      type: 'bar',
      showBackground: true,
      backgroundStyle: {
        color: 'rgba(180, 180, 180, 0.2)'
      }
    }
  ]
}

onMounted(() => {
  initChart()
})

const initChart = () => {
  if (barChart.value) {
    chart = echarts.init(barChart.value)
    chart.setOption(option)
  }
}

const updateChart = () => {
  const option_ = {
    xAxis: {
      data: props.xData
    },
    series: [
      {
        data: props.yData
      }
    ]
  }
  chart.setOption(option_)
}

// 更新图表
watch(props, (v) => {
  updateChart()
})
</script>

<style lang="scss" scoped>
.chart-box {
  border: 1px solid red;
}
</style>
